<template>
	<view class="content column">
		<view class="cenbox">
			<view class="title row">
				<view class="tit fill">充值金额</view>
				<!-- <view class="txt">账户余额<text class="balance">0</text>元</view> -->
			</view>
			<view class="inputBox">
				<input
				    placeholder="请输入充值金额，单次充值最高2000元"
				    class="input"
					type="digit"
				    v-model="rechargeAmount"
					@input="inputAmount"
				  >
			</view>
		</view>
		<view class="btnbox fill column">
			<view class="fill">
				<view class="title">支付方式</view>
				<view class="radiobox">
					<radio-group @change="radioChange">
						<label class="radio-list row" v-for="(item, index) in payList" :key="item.value">
							<view class="icon">
								<img :src="item.icon" class="img" alt="">
							</view>
							<view class="intro fill">
								<view class="name">{{item.name}}</view>
								<view class="desc">{{item.desc}}</view>
							</view>
							<view class="radio">
								<radio :value="item.value" :checked="index === current" />
							</view>
						</label>
					</radio-group>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<!-- <button type="default" class="btn-primary" v-if="!hasOpenId" open-type="getPhoneNumber" :disabled="isClick1" :class="{'isClick-style':isClick1}" @getphonenumber="wxChatLogin">确认支付</button> -->
			<button type="default" class="btn-primary" v-if="!hasOpenId" :disabled="isClick1" :class="{'isClick-style':isClick1}" @click="wxChatLogin">确认支付</button>
			<view v-else class="btn-primary" :class="{'isClick-style':isClick2}" @click="goPayRight">确认支付</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
				<view class="btn-primary" :class="{'isClick-style':isClick2}" @click="goPayRight">确认支付</view>
			<!-- #endif -->
			<!-- <button class="btn-primary" @click="submit">确认支付</button> -->
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref,reactive,nextTick } from 'vue'
import { onLoad } from "@dcloudio/uni-app"
import config from '@/utils/config'
import { financeRecharge } from '@/common/API/bills'
import { payOrder } from '@/common/API/pay'
import { getOpenId, getPhone } from '@/common/API/wxchat'
import {debounce} from '@/utils/debounce'
import store from '@/store'
const rechargeAmount = ref()
const winH = ref()
const current = ref(0)
const payList = ref([])
const isClick1 = ref(false)
const isClick2 = ref(false)

// #ifdef MP-WEIXIN
payList.value = [{
	value: 'yinlian_wx_miniapp',
	name: '微信支付',
	desc: '微信安全支付',
	icon: config.imgUrl+'/icon/wechat.png',
}]
// #endif
// #ifndef MP-WEIXIN
payList.value = [{
	value: 'yinlian_wx_miniapp',
	name: '微信支付',
	desc: '微信安全支付',
	icon: config.imgUrl+'/icon/wechat.png',
},{
	value: 'yinlian_alipay_app',
	name: '支付宝支付',
	desc: '支付宝安全支付',
	icon: config.imgUrl+'/icon/ali.png',
	checked: 'true'
}]
// #endif

const params = reactive({
	"appId": config.appId,
	"channelCode": 'tonglian_wx_miniapp',
	"sourceBizId": null,
	"sourceBizType": 'ACCOUNT_RECHARGE'
})

const hasOpenId = ref(false)
const custId = ref()  //账户id
const custType = ref() //账户类型INDIVIDUAL个人/COMPANY企业/ROOM房屋
onLoad((options)=> {
	let openId = uni.getStorageSync("openId");
	hasOpenId.value = openId? true : false
	winH.value = uni.getWindowInfo().windowHeight+"px";
	custId.value = options.custId
	custType.value = options.custType
})

const radioChange = (evt)=> {
	for (let i = 0; i < payList.value.length; i++) {
		if (payList.value[i].value === evt.detail.value) {
			current.value = i;
			params.channelCode = evt.detail.value
			break;
		}
	}
	isClick1.value = false
	isClick2.value = false
}

const inputAmount = (e)=>{
	nextTick(()=>{
		let value = e.detail.value
		if(value === '') {
			return false
		}
		const dotIndex = value.indexOf(".");
		const dotLastIndex = value.lastIndexOf(".");
		if (dotIndex !== dotLastIndex) {
			value = value.slice(0, dotLastIndex);
		}
		const pieces = value.split('.', 2)
		if(pieces.length === 2 && pieces[1].length > 2) {
			pieces[1] = pieces[1].substring(0, 2)
			rechargeAmount.value = pieces.join('.')
		}
		rechargeAmount.value = pieces.join('.')
	})
}

//去支付
const goPayRight = () => {
	if(!rechargeAmount.value){
		uni.showToast({
			title:'请输入充值金额',
			icon: 'none'
		})
    isClick1.value = false
		return
	}else if(rechargeAmount.value>2000){
		uni.showToast({
			title:'单次充值最高2000元',
			icon: 'none'
		})
    isClick1.value = false
		return
	}

	if(isClick2.value){
		return
	}else{
		isClick2.value = true
	}
	submit()
}

const submit = async () => {
  params.sourceBizId = await financeRecharge({
    rechargeAmount: rechargeAmount.value,
    custId: custId.value,
    custType: custType.value
  })
  if(current.value==0){
    // 微信支付
    //app调起微信小程序
    // #ifdef APP-PLUS
    plus.share.getServices(function(res){
      var sweixin = null;
      for (var i = 0; i < res.length; i++) {
        var t = res[i];
        if (t.id == 'weixin') {
          sweixin = t;
        }
      }
      if (sweixin) {
        let loginInfo = {
          userPhone: uni.getStorageSync('userPhone'),
          accessToken: uni.getStorageSync('accessToken'),
          userId: uni.getStorageSync('userId'),
          tenentId: uni.getStorageSync('tenentId')
        }
        sweixin.launchMiniProgram({
          id: config.wxChatAppId,
          type: config.type,
          path: `/pages/internal/index?loginInfo=${encodeURIComponent(JSON.stringify(loginInfo))}&url=${encodeURIComponent(`/pages/personal/pay/index?id=${params.sourceBizId}&type=${params.sourceBizType}&payStatus=${true}`)}`//这里是指定页的路径，如需传参直接字符串拼接（首页可以省略）
        });
        setTimeout(()=>{
          uni.navigateBack()
        },3000)
      }
    }, function(e){
        console.log();
    });
    // #endif
    //微信小程序支付
    // #ifdef MP-WEIXIN
    // let openId = uni.getStorageSync("openId")
    // if(openId){
      let data = {
        // "appId": config.wxchatId,
        "appId": config.appId,
        "channelCode": params.channelCode,
        "sourceBizId": params.sourceBizId,
        "sourceBizType": params.sourceBizType,
        // "channelExtras":  {
        //      "appId": config.NewWxChatAppId,
        //      "openId" : openId || ''
        // }
      }
      let res = await payOrder(data)
      if(res){
        // let orderInfo = JSON.parse(res.displayContent)
        // console.log(orderInfo)
        // wx.requestPayment({
        //   "timeStamp": orderInfo.timeStamp,
        //   "nonceStr": orderInfo.nonceStr,
        //   "package": orderInfo.package,
        //   "signType": orderInfo.signType,
        //   "paySign": orderInfo.paySign,
        //   "success":function(res){
        //     if(res){
        //       uni.redirectTo({
        //         url: '/pages/personal/cardbag/index'
        //       })
        //     }
        //     isClick1.value = false
        //     isClick2.value = false
        //   },
        //   "fail":function(res){
        //     console.log(res.errMsg)
        //     if(res.errMsg){
        //       uni.showToast({
        //         title: '支付失败',
        //         icon: 'error'
        //       });
        //     }
        //     isClick1.value = false
        //     isClick2.value = false
        //   },
        //   "complete":function(res){
        //     if(res){
        //       uni.redirectTo({
        //         url: '/pages/personal/cardbag/index'
        //       })
        //     }
        //     isClick1.value = false
        //     isClick2.value = false
        //   }
        // })
        const extraData = JSON.parse(res.otherContent)
        wx.openEmbeddedMiniProgram({
          appId: 'wxef277996acc166c3',
          extraData: extraData,
          success(res){
            isClick1.value = false
            isClick2.value = false
            uni.redirectTo({
              url: '/pages/personal/cardbag/index'
            })
          },
          fail(err){
            isClick1.value = false
            isClick2.value = false
          }
        })
      }
    // }
    // #endif
  }else if(current.value==1){
    // 支付宝
    let res = await payOrder(params)
    console.log('支付宝params:'+params)
    console.log('支付宝res:'+res)
    if(res){
      let url = JSON.parse(res.displayContent).qrCode
      let platform = uni.getSystemInfoSync().platform;//获取平台判断
      if (platform == 'android') {
        plus.runtime.openURL(url)
      } else if (platform == 'ios') {
        plus.runtime.launchApplication({
          action: url
        })
      }
      setTimeout(()=>{
        uni.navigateBack()
      },3000)
    }
    isClick1.value = false
    isClick2.value = false
  }
}

const wxChatLogin = debounce(async () => { //微信授权登录
	if(isClick1.value){
		return
	}else{
		isClick1.value = true
	}
	// let openId = uni.getStorageSync("openId");
	// if (!openId) {
	// 	//获取手机号
	// 	// let p = {
	// 	// 	appId: config.NewWxChatAppId,
	// 	// 	code: e.detail.code
	// 	// }
	// 	// console.log(p)
	// 	// let phone = await getPhone(p)
	// 	// console.log(phone)
	// 	// 获取openId
	// 	uni.login({
	// 		provider: 'weixin',
	// 		success: (res) => {
	// 			let data = {
	// 				appId: config.NewWxChatAppId,
	// 				code: res.code
	// 			}
	// 			console.log(data)
	// 			getOpenId(data).then((openIdstr)=>{
	// 				store.dispatch("SET_OPENID", openIdstr);
	// 				submit()
	// 			})
	// 		}
	// 	})
	// }else{
	// 	goPayRight()
	// }
  goPayRight()
}, 500)
</script>
<style>
	page{
		height: 100%;
	}
</style>
<style scoped lang="scss">
.content{
	padding-top: 16rpx;
	display: flex;
	height: 100%;
	.cenbox{
		background: #fff;
		margin: 0 0 16rpx;
		padding: 30rpx 32rpx 60rpx;
		.title{
			margin-bottom: 24rpx;
			.tit{
				font-size: 32rpx;
				font-weight: bold;
			}
			.txt{
				color: #666;
				.balance{
					font-size: 32rpx;
					font-weight: bold;
					padding: 0 10rpx;
				}
			}
		}
	}
	.inputBox{
		.input{
			border: 2rpx solid #f5f5f5;
			border-radius: 8rpx;
			height: 78rpx;
			line-height: 78rpx;
			padding: 0 16rpx;
		}
	}
	.btnbox{
		background: #fff;
		padding: 30rpx 32rpx 70rpx;
		.title{
			font-size: 32rpx;
			font-weight: bold;
		}
		.radiobox{
			.radio-list{
				border-bottom: 2rpx solid #f5f5f5;
				padding: 20rpx 0;
				.icon{
					width: 48rpx;
					height: 48rpx;
				}
				.intro{
					margin: 0 20rpx;
					.name{
						line-height: 38rpx;
					}
					.desc{
						font-size: 24rpx;
						line-height: 36rpx;
						color: #999;
					}
				}
			}
		}
		.btn-primary{
			width: 100%;
			border-radius: 10rpx;
			background: $uni-color-primary;
			color: #fff;
		}
		.isClick-style{
			background: rgba(219, 219, 219, 1);
		}
	}
}
</style>
